<template>
  <div class="Document">
     <a-modal v-model="visible" title="查看已勾选的文件" @ok="visible = false" :width="900" :dialogStyle="{'top':'30px'}" :forceRender="true">
       <div style="height:500px;">
         <div  style="display:flex;margin-bottom:5px;  justify-content: space-between;">
             <div></div>
             <div>
                <a-button type="primary" icon="copy" style="margin-left: 5px" @click="beforePdfMarge" :loading="margeloading">文件合并</a-button>
                <a-button type="primary" icon="file-zip" style="margin-left: 5px" :loading="collectloading" @click="beforeFileCollect">文件打包</a-button>
             </div>
         </div>
         <a-row type="flex">
           <a-col span="1" style="text-align : center">序号</a-col>
            <a-col span="12">文件名</a-col>
            <a-col span="9">所属路径</a-col>
             <a-col span="2" style="text-align : center">操作</a-col>
         </a-row>
         <a-list :data-source="selectedFiles" style="height:450px; overflow: auto;" :loading="listLoading" ref="cartList">
          <a-list-item slot="renderItem" slot-scope="item,index">
            <a-row type="flex" style="width: 100%; cursor:pointer" justify="start" > 
              <a-col span="1" style="text-align : center">{{index+1}}</a-col>
              <a-col span="12 ">{{item.name}}</a-col>
              <a-col span="9">{{item.path}}</a-col>
              <a-col span="2" style="text-align : center"> 
                <a-button type="danger" size="small" icon="delete" @click="deleteSelectedFile(item)"></a-button> 
              </a-col>
          </a-row>
          </a-list-item>
        </a-list>
       </div>

    </a-modal>
 
    <div class="files-count ng-binding">
        共 {{ total }} 个文件 
    </div>
    <a-row type="flex" justify="space-between" align="middle">
      <a-col style="">
        <a-space>
         <a-input
          placeholder="输入文件名模糊查询"
          enter-button="搜索"
          v-model="filename"
          @keyup.enter.native="onSearch"
          style="width:350px"
        />
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button type="primary" @click="filename = '';searchFileList=[]">重置</a-button>
        </a-space>
      </a-col>
      <a-col>
         <div style="position: relative;">
          <a-button type="primary" size="large" icon="folder" @click="showCart" />
          <span class="text_span">{{selectedFiles.length > 99 ? 99 : selectedFiles.length}}</span>  
       </div>
      </a-col>
    </a-row>
      <!-- <SearchFiles @finddata="getData"/> -->

        <a-checkbox-group style="width: 100%" :value="value">
    <div v-show=" searchFileList.length == 0">
      <div class="main-content" >
        <img class="logo" src="@/assets/logo/folder.png" alt="" />
        <a-space>
          <template v-for="(path, i) in parentPath">
            <span v-if="i != 0" :key="i">></span>
            <span
              :key="path.uuid"
              class="cursor"
              style="margin-left: 5px"
              @click="getData(path.uuid)"
              >{{ path.name }}</span
            >
          </template>
        </a-space>

        <div style="margin-left: auto">
          <a-button type="danger"  icon="profile" style="margin-left: 5px" @click="sendData" :loading="sendDataloading" >文件归档</a-button>
        </div>
      </div>

      <ul class="file-list template-doc-list">
        <div class="file-banner">
          <div class="action"></div>
          <div class="title">
            <span class="filename un-editable">文件名</span>
          </div>
          <div class="size">文件大小</div>
        </div>
      
          <a-empty v-if="path.length == 0" />
          <li class="file-item" v-for="item in path" :key="item.uuid">
            <div class="action">
              <a-checkbox v-if="item.type != 0" :value="item.id"   @change="(e)=> change(e,item)"></a-checkbox>
            </div>
            <div class="title cursor">
              <img
                v-if="item.type == 0"
                class="logo2"
                src="@/assets/logo/folder.png"
                alt=""
              />
              <img
                v-if="item.type == 1"
                class="logo2"
                src="@/assets/logo/pdf.png"
                alt=""
              />
              <img
                v-if="item.type == 2"
                class="logo2"
                src="@/assets/logo/word.png"
                alt=""
              />
              <img
                v-if="item.type == 3"
                class="logo2"
                src="@/assets/logo/excel.png"
                alt=""
              />
              <img
                v-if="item.type == 4"
                class="logo2"
                src="@/assets/logo/txt.png"
                alt=""
              />
              <img
                v-if="item.type == 5"
                class="logo2"
                src="@/assets/logo/png.png"
                alt=""
              />
              <span
                @click="item.type == 0 ? getData(item.uuid) : gotoPDFOCR(item.id)"
                >{{ item.name }}</span
              >
            </div>
            <div class="size">{{ item.size }}</div>
          </li>
       
      </ul>
    </div>
    <div v-show="searchFileList.length != 0">
       <ul class="file-list template-doc-list">
        <div class="file-banner">
          <div class="action"></div>
          <div class="title">
            <span class="filename un-editable">文件名</span>
          </div>
          <div class="size">所在路径</div>
        </div>
        <!-- <a-checkbox-group style="width: 100%" :value="value"> -->
          <li class="file-item" v-for="item in searchFileList" :key="item.id">
            <div class="action">
              <a-checkbox :value="item.id"  @change="(e)=> change(e,item)"></a-checkbox>
            </div>
            <div class="title cursor">
              <img
                v-if="item.type == 0"
                class="logo2"
                src="@/assets/logo/folder.png"
                alt=""
              />
              <img
                v-if="item.type == 1"
                class="logo2"
                src="@/assets/logo/pdf.png"
                alt=""
              />
              <img
                v-if="item.type == 2"
                class="logo2"
                src="@/assets/logo/word.png"
                alt=""
              />
              <img
                v-if="item.type == 3"
                class="logo2"
                src="@/assets/logo/excel.png"
                alt=""
              />
              <img
                v-if="item.type == 4"
                class="logo2"
                src="@/assets/logo/txt.png"
                alt=""
              />
              <img
                v-if="item.type == 5"
                class="logo2"
                src="@/assets/logo/png.png"
                alt=""
              />
              <span
                @click="gotoPDFOCR(item.id)"
                >{{ item.name }}</span
              >
            </div>
            <div class="size">{{ item.path }}</div>
          </li>
        <!-- </a-checkbox-group> -->
      </ul>
    </div>
     </a-checkbox-group>

      <a-modal  v-model="isShowRenameFile" title="请输入打包文件名" 
                 @ok="packFiles" okText="确定" 
                 @cancel="cancelPackFiles" cancelText="取消">
               <a-input v-model="packFileName" placeholder="打包文件名" />
       </a-modal>

        <a-modal  v-model="isShowMargeName" title="请输入合并文件名" 
                 @ok="pdfReady" okText="确定" 
                 @cancel="cancelMargeFiles" cancelText="取消">
               <a-input v-model="margeFileName" placeholder="合并文件名" />
       </a-modal>
  </div>
</template>

<script>
import { searchFiles, getFile, pdfMarge,sendData,fileCollect,saveCart,getCart,deleteCartFile,sortCartFile } from "@/request/api";
import Sortable from 'sortablejs' 
// import SearchFiles from '@/components/SearchFiles'
export default {
  name: "Document",
  // components: {SearchFiles},
  data() {
    return {
      id:-2,
      data: {},
      olddata: {},
      total: 0,
      path: [],
      parentPath: [],
      pdfGroup: [],
      type: 0,
      margeloading:false,
      sendDataloading:false,
      collectloading:false,
      selectedFiles : [],
      visible: false,
      value : [],
      isShowRenameFile:false,
      packFileName:'',
      isShowMargeName:false,
      margeFileName:'',
      listLoading:false,
      filename:'',
      searchFileList:[]
    };
  },
  mounted() {
    this.id = this.$route.params.id;
    this.getFile();
    this.getCart()
    setTimeout(()=>{
        this.rowDrop()
    },500)
    
  },
  methods: {
    rowDrop () {
    
       const ul = this.$refs.cartList.$el.querySelector('.ant-list-items')
       if(!ul){
         console.error("拖拉功能绑定失败")
         return
       }
      const _this = this
      Sortable.create(ul, {
        animation: 150,
        onEnd ({ newIndex, oldIndex }) {
          if(newIndex != oldIndex){
            let params =  _this.selectedFiles.map(f => f.id)
            const currRow = params.splice(oldIndex,1)[0]
            params.splice(newIndex,0,currRow)
          
            sortCartFile(_this.id,params).then(()=>{
              // 排序成功后，手动把dom恢复原状
              // 移除新的dom
           
              _this.getCart(()=>{
                const newNode = ul.children[newIndex]
                ul.removeChild(newNode)
                if(oldIndex == ul.children.length-1){
                  ul.appendChild(newNode)
                }else{
                  const node = ul.children[oldIndex]
                  ul.insertBefore(newNode,node)
                }
              })

            }).catch(()=>{})
          }
        },
      })
    },
    getFile() {
      getFile(this.id)
        .then((data) => {
          this.total = data.total;
          this.data = data
           this.getData(this.data.uuid);
        })
        .catch(() => {});
    },
    getData(uuid) {
      this.findData(this.data, uuid, []);
    },
    findData(path, uuid, parentPath) {
      if (path.uuid == uuid) {
        this.path = path.sub;

        parentPath.push({
          uuid: path.uuid,
          name: path.name,
        });
        this.parentPath = parentPath;
        return true;
      } else {
        if (path.type != 0) {
          return false;
        }
        for (let i = 0; i < path.sub.length; i++) {
          let p = path.sub[i];
          let pp = JSON.parse(JSON.stringify(parentPath));
          pp.push({
            uuid: path.uuid,
            name: path.name,
          });
          let result = this.findData(p, uuid, pp);
          if (result) {
            return true;
          }
        }
      }
    },
    change(e,item){
      let target = e.target
      if(target.checked){
        saveCart(this.id,{
          id:item.id,
          name:item.name,
          path:item.path
        }).then(data=>{
          console.log(data)
          // this.selectedFiles.push(item)
          this.value.push(item.id)
          this.getCart()
        }).catch(e => {
          console.error(e)
        })
      
      }else{
        this.deleteSelectedFile(item)
      }
    },
    deleteSelectedFile(item){
        deleteCartFile(this.id,item.id).then(() => {
          // console.log(data)
          // this.selectedFiles.splice(this.selectedFiles.indexOf(item),1)
          this.value.splice(this.value.indexOf(item.id),1)
          this.getCart()
        }).catch(() => {
        })
    },
    showCart(){
      this.getCart(()=>{
        this.visible = true
      })
    },
    getCart(callback){
      this.listLoading = true
      getCart(this.id).then(data=>{
        // console.log(data)
        let selectedFiles = data
        let value = selectedFiles.map(e => e.id)
        
        Object.assign(this,{
          selectedFiles,
          value,
          listLoading : false
        })

        callback && callback()
      }).catch(()=>{
      })
    },
    gotoPDFOCR(did) {
      const pdfOCR = this.$router.resolve("/case/" + this.id + "/pdfOCR/" + did);
      window.open(pdfOCR.href, "_blank");
    },
    beforePdfMarge(){
      let params = this.value;
      console.log(params);
      if (params.length <= 0) {
        this.$message.error("未勾选数据");
        this.margeloading=false
        return;
      }
        this.isShowMargeName  = true
    },
    pdfReady(){

       if(this.margeFileName == ''){
          this.$message.error("命名不能为空");
          return
        }
        this.pdfMarge(this.margeFileName,this.value)
        this.isShowMargeName = false
        this.margeFileName=''
    },
    cancelMargeFiles(){
        this.isShowMargeName = false
        this.margeFileName=''
    },
    pdfMarge(fileame,params) {
      //获取url参数
      this.margeloading = true
      let caseId = this.id
      pdfMarge(fileame,params,caseId)
        .then(() => {
          this.margeloading = false
          this.$message.success("合并成功");
          this.pdfGroup = [];
        })
        .catch(() => {this.margeloading=false;this.margeFileName=''});
    },
    sendData(){
      this.sendDataloading=true
      let params = this.value;
      if (params.length <= 0) {
        this.$message.error("未勾选数据");
        this.sendDataloading=false
        return;
      }
      sendData(this.id,params)
        .then((data) => {
           console.log(data)
             this.sendDataloading=false
           this.$message.success("文件归档成功");
        
        })
        .catch(() => {  this.sendDataloading=false});
    },
    //文件打包
    beforeFileCollect(){
       let params = this.value;
       if (params.length <= 0) {
        this.$message.error("未勾选数据");
        this.collectloading=false
        return;
      }
      this.isShowRenameFile = true
    },
    fileCollect(name,params){
       this.collectloading=true
       fileCollect(name,params)
        .then((data) => {
          this.collectloading = false
          window.open(data);
          this.$message.success("打包成功");
          this.pdfGroup = [];
        })
        .catch(() => {this.collectloading=false});
    },
    packFiles(){
        if(this.packFileName == ''){
          this.$message.error("命名不能为空");
          return
        }
        this.fileCollect(this.packFileName,this.value)
        this.isShowRenameFile = false
        this.packFileName=''

    },
    cancelPackFiles(){
      this.isShowRenameFile = false
      this.packFileName=''
    },
    onSearch(){
      if(this.filename == ''){
        this.searchFileList=[]
        return false
      }
      searchFiles(this.id,this.filename).then(data =>{
        this.searchFileList = data
        if(this.searchFileList.length == 0){
          this.$message.info('没有检索到任何文件')
        }
      }).then(()=>{
      })
    }
  },
};
</script>
<style scoped>
.Document {
  height: 100%;
  font: 14px/1.5 "PingFang SC", "Hiragino Sans GB", "Microsoft Yahei",
    sans-serif;
  padding: 10px;
}

.cursor {
  cursor: pointer;
}
.logo {
  width: 25px;
  height: 25px;
}
.logo2 {
  width: 15px;
  height: 15px;
  margin-right: 10px;
}
.files-count {
  color: #a6a6a6;
  font-size: 12px;
  display: flex;
  justify-content: space-between;
}
.main-content {
  display: flex;
  padding-top: 10px;
  align-items: center;
  margin-bottom: 10px;
}

.template-doc-list {
  clear: both;
}
.file-banner {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f0f0f0;
  line-height: 36px;
}
.file-banner div {
  width: 33em;
  height: 36px;
  display: inline-block;
  text-align: left;
  line-height: 36px;
}
.file-item div {
  width: 33em;
  height: 40px;
  display: flex;
  align-items: center;
}
.file-item {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #f0f0f0;
}
.action {
  width: 40px !important;
}

.text_span {
    position: absolute;
    font-size: 12px;
    background: red;
    width: 22px;
    height: 22px;
    line-height: 22px;
    border-radius: 50%;
    top: -8px;
    right: -8px;
    text-align: center;
    color: #fff;
}
</style>